<?php

namespace app\librarys;

/**
 * 数据库缓存
 * Class DbCacheUtility
 * @package app\librarys
 */
class DbCacheUtility
{
    /**
     * @param $cmd \Yii\db\Command
     * @param $cacheDuration int    缓存时间. 如果为0,则重新从数据库取数据.
     * @return mixed
     */
    public static function queryAll($cmd, $cacheDuration = 60)
    {
        $key = 'query_all:' . md5($cmd->getRawSql());

        if ($cacheDuration == 0) {
            if (\Yii::$app->cache->exists($key)) {
                \Yii::$app->cache->delete($key);
            }
        }

        if (!(\Yii::$app->cache->exists($key))) {
            $result = $cmd->queryAll();
            if ($cacheDuration != 0) {
                \Yii::$app->cache->set($key, $result, $cacheDuration);
            }
        } else {
            $result = \Yii::$app->cache->get($key);
        }

        return $result;
    }

    /**
     * @param $cmd \Yii\db\Command
     * @param $cacheDuration int    缓存时间. 如果为0,则重新从数据库取数据.
     * @return mixed
     */
    public static function queryOne($cmd, $cacheDuration = 60)
    {
        $key = 'query_one:' . md5($cmd->getRawSql());

        if ($cacheDuration == 0) {
            if (\Yii::$app->cache->exists($key)) {
                \Yii::$app->cache->delete($key);
            }
        }

        if (!(\Yii::$app->cache->exists($key))) {
            $result = $cmd->queryOne();
            if ($cacheDuration != 0) {
                \Yii::$app->cache->set($key, $result, $cacheDuration);
            }
        } else {
            $result = \Yii::$app->cache->get($key);
        }
        return $result;
    }

    /**
     * @param $cmd \Yii\db\Command
     * @param $cacheDuration int    缓存时间. 如果为0,则重新从数据库取数据.
     * @return mixed
     */
    public static function queryScalar($cmd, $cacheDuration = 60)
    {
        $key = 'query_scalar:' . md5($cmd->getRawSql());

        if ($cacheDuration == 0) {
            if (\Yii::$app->cache->exists($key)) {
                \Yii::$app->cache->delete($key);
            }
        }

        if (!(\Yii::$app->cache->exists($key))) {
            $result = $cmd->queryScalar();
            if ($cacheDuration != 0) {
                \Yii::$app->cache->set($key, $result, $cacheDuration);
            }
        } else {
            $result = \Yii::$app->cache->get($key);
        }
        return $result;
    }
}